<template>
    <Form @success="searchModel.pageNo = 1; getList()" :loading="loading" v-valid="['goodsSearch', 'goodsAdd']" inline
        labelWidth="70px" :options="searchOptions" :model="searchModel" reset="重置" @add="goods = {}; dfRef.show();"
        add="添加商品" submit="搜索" addCode="goodsAdd" formCode="goodsSearch">
    </Form>
    <Table v-valid="'goodsSearch'" :data="list" :cols="cols" :total="total" v-model:page="searchModel">
        <template #creation_time="{ row: { creation_time } }">
            {{ dayjs(creation_time).format(dateType) }}
        </template>
        <template #status="{ row: { status } }">
            {{ status ? '上架' : '下架' }}
        </template>
        <template #action="{ row }">
            <ElButton @click="goods = { ...row }; dfRef.show();" v-valid="'goodsUpdate'" type="primary">修改</ElButton>
            <ElButton v-valid="'goodsChangeStatus'" type="danger" @click="change(row)">{{ row.status ? '下架' : '上架' }}
            </ElButton>
        </template>
    </Table>
    <DF @ok="confirmGoods" :model="goods" labelWidth="80px" v-valid="['goodsAdd', 'goodsUpdate']" ref="dfRef"
        :options="addUpdateOptions" :title="goods.id ? '修改商品' : '添加商品'" />
</template>

<script lang="ts" setup>
import { computed, ref } from "vue"
import { add, update, search, changeStatus, IAddGoods, UpdateGoodsType, ChangeGoodsStatusType, SearchType, IGoods } from '@/api/goods';
import { getAll, IClassify } from '@/api/classify';
import { valid } from '@/utils/common';
import { dateType } from '@/utils/consts';
import ask from '@/components/Confirm';
import dayjs from 'dayjs';

/**
 * 搜索业务开始
 */

/**
 * 搜索模型
 */
const searchModel = ref(<SearchType>{
    pageNo: 1,
    pageSize: 10,
    status: '' as any,
    class_id: '' as any
});
/**
 * 分类列表
 */
const classList = ref<IClassify[]>([]);
/**
 * loading
 */
const loading = ref(false);
/**
 * 列
 */
const cols = {
    name: {
        title: '商品名称'
    },
    price: {
        title: '商品价格'
    },
    oldPrice: {
        title: '旧价格'
    },
    sku: {
        title: '库存'
    },
    quantity: {
        title: '剩余总数'
    },
    weight: {
        title: '重量'
    },
    status: {
        title: '状态'
    },
    creation_time: {
        title: '创建时间'
    },
    'classify.name': {
        title: '所属分类'
    },
    action: {
        title: '操作'
    }
}
/**
 * 商品列表
 */
const list = ref<IGoods[]>([]);
/**
 * 总条数
 */
const total = ref(0);
/**
 * 搜索表单配置项
 */
const searchOptions = computed(() => ({
    name: {
        title: '商品名称',
        max: 100
    },
    price: {
        title: '最低价格',
        type: 'number',
        width: '80px',
    },
    end_price: {
        title: '最高价格',
        type: 'number',
        width: '80px',
    },
    status: {
        title: '状态',
        tag: 'select',
        width: '80px',
        values: [{ label: '所有', value: '' }, { label: '上架', value: 1 }, { label: '下架', value: 0 }]
    },
    class_id: {
        title: '分类',
        tag: 'cascader',
        values: [{ label: '所有', value: '' }, ...classList.value.filter(c => c.pid === 0).map(({ name: label, id: value }) => ({
            label,
            value,
            children: classList.value.filter(d => d.pid === value).map(({ name: label, id: value }) => ({ label, value }))
        }))]
    }
}));

/**
 * 获取列表
 */
const getList = async () => {
    try {
        loading.value = true;
        const { class_id } = searchModel.value;
        //@ts-ignore
        searchModel.value.class_id = class_id instanceof Array ? class_id.slice(-1)[0] : class_id;
        const { data, count } = await search(searchModel.value);
        total.value = count;
        list.value = data;
    } catch (error) { }
    loading.value = false;
}

(async () => {
    if (valid('goodsSearch')) {
        getList();
    }
    if (valid('goodsSerch') || valid('goodsAdd')) {
        try {
            classList.value = await getAll();
        } catch (error) { }
    }
})();

/**
 * 搜索业务结束
 */

// 添加修改业务开始

/**
 * 要修改的和添加的商品信息对象
 */
const goods = ref(<UpdateGoodsType & IAddGoods>{});
/**
 * df引用
 */
const dfRef = ref();
/**
 * 添加修改表单配置项
 */
const addUpdateOptions = computed(() => ({
    name: {
        title: '商品名称',
        required: true,
        max: 100
    },
    class_id: {
        title: '分类',
        tag: 'cascader',
        required: true,
        values: classList.value.filter(c => c.pid === 0).map(({ name: label, id: value }) => ({
            label,
            value,
            children: classList.value.filter(d => d.pid === value).map(({ name: label, id: value }) => ({ label, value }))
        }))
    },
    price: {
        title: '价格',
        type: 'number',
        required: true,
        min: 0,
    },
    oldPrice: {
        title: '旧价格',
        type: 'number',
        required: true,
        min: 0,
    },
    sku: {
        title: '库存',
        type: 'number',
        required: true,
        min: 1,
    },
    ...(goods.value.id && {
        quantity: {
            title: '剩余数量',
            type: 'number',
            required: true,
            min: 0
        }
    }),
    weight: {
        title: '重量',
        type: 'number',
        required: true,
        min: 0,
    }
}));

/**
 * 提交商品
 * @param model 
 */
const confirmGoods = async (model: IAddGoods & UpdateGoodsType) => {
    try {
        const { class_id } = model;
        //@ts-ignore
        delete model.classify;
        //@ts-ignore
        delete model.status;
        //@ts-ignore
        delete model.creation_time;
        //@ts-ignore
        model.class_id = class_id instanceof Array ? class_id.slice(-1)[0] : class_id;
        await (model.id ? update : add)(model);
        getList();
        dfRef.value.hide();
    } catch (error) { }
    dfRef.value.stop();
}

// 添加修改业务结束

// 修改状态业务开始

/**
 * 更改状态
 * @param param0 
 */
const change = async ({ name, id, status }: IGoods) => {
    let res: any;
    try {
        res = await ask(`您确定要${status ? '下架' : '上架'}【${name}】吗？`);
        await changeStatus({ id, status: status ? 0 : 1 });
        getList();
    } catch (error) { }
    res && res();
}

// 修改状态业务结束

</script>
<style lang="scss" scoped></style>